import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A Servlet to help view jpg images
 *
 * @author James Chy
 */

public class OneImage extends PhotoServlet {

	static final long serialVersionUID = 0;
    
    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
    }
        
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();

        String image=request.getParameter("image");        
        String sessionid=request.getParameter("sessionid");        
        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");

        String title = "Image " + image;

        out.println("<title>" + title + "</title>");  
        out.println("</head>");
        out.println("<body>");

        out.println("<TABLE BORDER=1><TR><TD VALIGN=TOP>");
        out.println("<FORM ACTION=\"OneImageUpdate\" METHOD=\"GET\">");
        out.println("<INPUT TYPE=HIDDEN NAME=\"image\" VALUE=\"" + image + "\">");
        out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
        out.println("<INPUT TYPE=HIDDEN NAME=\"sessionid\" VALUE="+sessionid+">");
        if(updatebtn)
           out.println("<INPUT TYPE=SUBMIT VALUE=\"Update\">");
        out.println("</FORM>");
        out.println("</TD>");

        try
        {

            String query;
            ResultSet rs;
            String image_uid="";
            String description = "";
            int count=0;

            // Get image_uid
            query = "SELECT images.uid, images.description FROM images " +
                    "WHERE TRIM(images.image_file) = \"" + image + "\"";
            if(showQuery) out.println("Query: " + query + "<BR>");
            rs = executeQuery(query);
            while(rs.next())
            {
            	image_uid = rs.getString("images.uid"); 
			    description = rs.getString("images.description"); 
            } 

            query = "SELECT session_uid, image_file FROM session_results " +
                    "WHERE session_uid = " + sessionid + " ORDER BY (date) DESC, (image_file) DESC;";
            if(showQuery) out.println("Get session: " + query + "<BR>");
            rs = executeQuery(query);
            while(rs.next())
            {
                if(rs.getString("image_file").equals(image) && !rs.isFirst())
                {
                    rs.previous();
                    String prev=rs.getString("image_file");
                    out.println("<TD VALIGN=TOP>");
                    out.println("<FORM ACTION=OneImage METHOD=GET>");
                    out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+prev+"\">");
                    out.println("<INPUT TYPE=SUBMIT VALUE=Prev>");
                    out.println("</FORM>");
                    out.println("</TD>");
                    rs.next();
                }
                if(rs.getString("image_file").equals(image) && !rs.isAfterLast() && !rs.isLast())
                {
                    rs.next();
                    String next=rs.getString("image_file");
                    out.println("<TD VALIGN=TOP>");
                    out.println("<FORM ACTION=OneImage METHOD=GET>");
                    out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+next+"\">");
                    out.println("<INPUT TYPE=SUBMIT VALUE=Next>");
                    out.println("</FORM>");
                    out.println("</TD>");
                }
            }
                    
            out.println("<TD VALIGN=TOP>");
            out.println("<FORM ACTION=\"SearchResults\" METHOD=\"POST\">");
            out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
            out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
            out.println("<INPUT TYPE=SUBMIT VALUE=\"Search Results\">");
            out.println("</FORM>");
            out.println("</TD>");

            String oversizeFileName = oversize+File.separator+image;
            if(showQuery)
               out.println("Oversize File: " + oversizeFileName);
            File oversizeFile = new File(oversizeFileName);
            if(showQuery) 
               out.println("Oversize File Exists: "+String.valueOf(oversizeFile.exists()));
            if(oversizeFile.exists())
            {
                out.println("<TD VALIGN=TOP>");
                out.println("<FORM ACTION=\"OversizeDisp\" METHOD=\"POST\" TARGET=\"ovr\">");
                out.println("<INPUT TYPE=HIDDEN NAME=\"image\" VALUE=\"" + image + "\">");
                out.println("<INPUT TYPE=SUBMIT VALUE=\"Full Size\">");
                out.println("</FORM>");
            	out.println("</TD>");
            }
            out.println("</TR></TABLE>");
            out.println("<TABLE><TR><TD VALIGN=TOP>");

            // Begin Dates
            query = "SELECT COUNT(*) FROM image_date WHERE image_date.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT dates.uid, dates.date, image_date.image_uid " +
                    "FROM dates " +
                    "LEFT OUTER JOIN image_date " +
                    "ON dates.uid = image_date.date_uid " +
                    "AND image_date.image_uid = " + image_uid + " " +
                    "ORDER BY dates.date DESC";
            rs = executeQuery(query);
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");
            out.println("<B>Dates</B><BR>");
            out.println("<TABLE>");

            if(count==0)
                out.println("<TR><TD>None</TD></TR>");

            while (rs.next()) 
            {
                String date = rs.getString("dates.date");   
                String outer = rs.getString("image_date.image_uid"); 
                if(outer!=null)
                    out.println("<TR><TD>"+OneImage.MonthDayYear(date)+"</TD></TR>");
            }
            out.println("</TABLE>");
            // End Dates

            out.println("</TD><TD VALIGN=TOP>");

            // Begin People
            query = "SELECT COUNT(*) FROM image_person WHERE image_person.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT people.*," +
                    " image_person.image_uid " +
                    "FROM people " +
                    "LEFT OUTER JOIN image_person " +
                    "ON people.uid = image_person.person_uid " +
                    "AND image_person.image_uid = " + image_uid + " " +
                    "ORDER BY people.lastName, people.firstName, people.middleName";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B>People</B><BR>");
            out.println("<TABLE>");

            if(count==0)
                out.println("<TR><TD>None</TD></TR>");

            while (rs.next()) 
            {
                String name=OneImage.FirstNameLastName(rs);
                String outer = rs.getString("image_person.image_uid"); 
                if(outer!=null)
                    out.println("<TR><TD>" + name + "</TD></TR>");
            }
            out.println("</TR></TABLE>");
            // End People

            out.println("</TD><TD VALIGN=TOP>");

            // Begin Things
            query = "SELECT COUNT(*) FROM image_thing WHERE image_thing.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT things.uid, things.thing, " +
                    " image_thing.image_uid " +
                    "FROM things " +
                    "LEFT OUTER JOIN image_thing " +
                    "ON things.uid = image_thing.thing_uid " +
                    "AND image_thing.image_uid = " + image_uid + " " +
                    "ORDER BY things.thing";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B>Things</B><BR>");
            out.println("<TABLE>");

            if(count==0)
                out.println("<TR><TD>None</TD></TR>");

            while (rs.next()) 
            {
                String thing = rs.getString("things.thing");    
                String outer = rs.getString("image_thing.image_uid"); 
                if(outer!=null)
                    out.println("<TR><TD>" + thing + "</TD></TR>");
            }
            out.println("</TABLE>");
            // End Things

            out.println("</TD><TD VALIGN=TOP>");

            // Begin Places
            query = "SELECT COUNT(*) FROM image_place WHERE image_place.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT places.uid, places.place, " +
                    " image_place.image_uid " +
                    "FROM places " +
                    "LEFT OUTER JOIN image_place " +
                    "ON places.uid = image_place.place_uid " +
                    "AND image_place.image_uid = " + image_uid + " " +
                    "ORDER BY places.place";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B>Places</B><BR>");
            out.println("<TABLE>");

            if(count==0)
                out.println("<TR><TD>None</TD></TR>");

            while (rs.next()) 
            {
                String place = rs.getString("places.place");    
                String outer = rs.getString("image_place.image_uid"); 
                if(outer!=null)
                     out.println("<TR><TD>" + place + "</TD></TR>");
            }
            out.println("</TABLE>");
            // End Places

            out.println("</TD></TR></TABLE>");
            out.println("</FORM>");

            out.println("<BR>");
            out.println("<TABLE>");
            out.println("<TR><TD><IMAGE SRC=\"" + imgmain + "/" + image + "\"></TD></TR>");
			out.println("<TR><TD>" + description + "</TD></TR>");
            out.println("</TABLE>");
        }
        catch(SQLException sqle)
        {
            out.println("SQL Exception");
        }
        
        out.println("</body>");
        out.println("</html>");

    }
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();
        
        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");

        out.println("<title>Post</title>");  
        out.println("</head>");
        out.println("<body>");


        if(showQuery)
        {
            for(Enumeration e=request.getParameterNames(); e.hasMoreElements(); )
            {
                String currentElement=e.nextElement().toString();
                String currentValues[]=request.getParameterValues(currentElement);
                for(int i=0; i<currentValues.length; i++)
                    out.println(currentElement + "[" + i + "]=" + 
                            currentValues[i] + "<BR>");
            }
            out.println("Description: " + request.getParameter("description") + "<BR>");
        }

/*
        	Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            java.sql.Connection conn;
*/
            String query;
/*
            Statement stmt;
            conn = DriverManager.getConnection(connection);
*/

            String image_uid = request.getParameter("image_uid");

            // Begin People
            query = "DELETE FROM image_person " +
                    "WHERE image_uid = " + image_uid;

            if(showQuery)
                out.println(query + "<BR>");

//            stmt = conn.createStatement();
            int count = executeUpdate(query);
            
            String peopleValues[]=request.getParameterValues("people");
            for(int i=0; i<peopleValues.length; i++)
            {
                if(!peopleValues[i].equals("0"))
                {
                    query = "INSERT INTO image_person " +
                            "SET image_uid = " + image_uid + "," +
                            "person_uid = " + peopleValues[i];
                    if(showQuery)
                        out.println(query + "<BR>");
                    count = executeUpdate(query);
                }
            }
            // End People

            // Begin Places
            query = "DELETE FROM image_place " +
                    "WHERE image_uid = " + image_uid;

            if(showQuery)
                out.println(query + "<BR>");

//            stmt = conn.createStatement();
            count = executeUpdate(query);
            
            String placeValues[]=request.getParameterValues("places");
            for(int i=0; i<placeValues.length; i++)
            {
                if(!placeValues[i].equals("0"))
                {
                    query = "INSERT INTO image_place " +
                            "SET image_uid = " + image_uid + "," +
                            "place_uid = " + placeValues[i];
                    if(showQuery)
                        out.println(query + "<BR>");
                    count = executeUpdate(query);
                }
            }
            // End Places

            // Begin Dates
            query = "DELETE FROM image_date " +
                    "WHERE image_uid = " + image_uid;

            if(showQuery)
                out.println(query + "<BR>");

            // stmt = conn.createStatement();
            count = executeUpdate(query);
            
            String dateValues[]=request.getParameterValues("dates");
            for(int i=0; i<dateValues.length; i++)
            {
                if(!dateValues[i].equals("0"))
                {
                    query = "INSERT INTO image_date " +
                            "SET image_uid = " + image_uid + "," +
                            "date_uid = " + dateValues[i];
                    if(showQuery)
                        out.println(query + "<BR>");
                    count = executeUpdate(query);
                }
            }
            // End Dates

            // Begin Things
            query = "DELETE FROM image_thing " +
                    "WHERE image_uid = " + image_uid;

            if(showQuery)
                out.println(query + "<BR>");

            // stmt = conn.createStatement();
            count = executeUpdate(query);
            
            String thingValues[]=request.getParameterValues("things");
            for(int i=0; i<thingValues.length; i++)
            {
                if(!thingValues[i].equals("0"))
                {
                    query = "INSERT INTO image_thing " +
                            "SET image_uid = " + image_uid + "," +
                            "thing_uid = " + thingValues[i];
                    if(showQuery)
                        out.println(query + "<BR>");
                    count = executeUpdate(query);
                }
            }
            // End Things

            // Begin Description
            String description=request.getParameter("description");
            query = "UPDATE images " +
                    "SET description = \"" + description + "\" " +
                    "WHERE uid = " + image_uid;

            if(showQuery)
                out.println(query + "<BR>");

            count = executeUpdate(query);
            // End Description

            out.println("<H1>Data Saved, updated " + String.valueOf(count) + "</H1>");
            out.println("<FORM ACTION=OneImage METHOD=GET>");
            out.println("<INPUT TYPE=SUBMIT VALUE=\"Return to Image\">");
            out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+request.getParameter("image")+"\">");
            out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
            out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE=\""+request.getParameter("sessionid")+"\">");
            out.println("</FORM>");
            //out.println("<A HREF=OneImage?image=" + request.getParameter("image") + 
            //            "><H3>Return to Previous Page</H3></A>");
            

        out.println("</BODY></HTML>");
    }
               
}



